<?php
class Orders extends  Controller
{
	public $userdata;
	public $_cache;
    function Orders()
    {
        parent::Controller();
      
		header("Content-Type: text/html; charset=utf-8");
		$this->userdata = checksession($this->session);
		
		$_cache_system = array();
    	if(file_exists("./data/system.cache.php"))
    	{
    		require './data/system.cache.php';
    		
    	}
        $this->_cache = $_cache_system;
    	$this->tp->assign("cache",$_cache_system);
    	$this->db->query("SET time_zone = '+8:00'");
		
		stop("对不起,系统正在维护,暂时不能提供服务,谢谢配合!");
    }
    
    
    function index()
    {
    	
    	$userinfo = array();
    	if($this->userdata)
    	{
    		$query = $this->db->query("select eatname,eateryid,foodtime from ".table("eatery")." where areaid=".$this->userdata["areaid"]." and islock=0");
	    	if($query->num_rows()>0)
	    	{
	    		$rs  = $query->result_array();
	    		
	    		$foodeatid = $rs[0]["eateryid"];
	    		$eat = geteatinfo($this->db,$rs[0]["eateryid"]);
	    		
	    		$foodlist = getfoodlist($this->db,$foodeatid);
	    		
	    		$this->tp->assign("foodlist",$foodlist);
	    		$this->tp->assign("company",$rs);
	    		$this->tp->assign("eat",$eat);
	    	   
	    		
	    	}
	    	$userinfo = getuserinfo($this->db,$this->userdata["userid"],array("balance"));
	    	
	    
    	}
    	 $this->tp->assign("balance",count($userinfo)>0?$userinfo["balance"]:'none');
    	 $islogin = empty($this->userdata)?1:0;
    	 $this->tp->assign("islogin",$islogin?"<script language=\"javascript\">window.onload = LoginWindow;</script>":"");
    	 $this->tp->show("orders");
    	
        
    }
    function record($page="")
    {
    	
    	
    	
    	   $this->jypage->SetAttr(array(
			  'table'=>table('orders')." as o left join ".table("users")." as u on o.userid=u.userid left join ".table("food")." as f on o.foodid=f.foodid left join ".table("eatery")." as c on f.eatid=c.eateryid",
			  'pagesize'=>40,
			  'page'=>empty($page)?1:$page,
			  'key'=>'o.ordersid',
			  'field'=>array("o.*","u.nickname","f.foodname","c.eatname"),
    	      'condition'=>" order by o.ordersid desc",
			  'where'=>"date(o.createtime) = curdate() and o.isdo=0",
		      'pageurl'=>_baseurl_."orders/record/",
			  ));
		 $this->jypage->SetDb($this->db);
		
		 $pagelist = $this->jypage->pages();
		 
		
		 
    	$pagestr = $this->jypage->SetPageStr();
    	
    	$this->tp->assign("pagestr",$pagestr);
    	$this->tp->assign("pagelist",empty($pagelist["ZeroPage"])?array():$pagelist["ZeroPage"]);
    
    	$this->tp->show("orders_record");
    	
    }
    function docart()
    {
    	$result = array("error"=>1,"content"=>"对不起,已超过统计时间段,现无法订餐");
    	$obj = $_POST["obj"];
    	$run = $_POST["run"];
    	#if(dotime($this->_cache["endtime"]))
    	#{
    		$this->load->library("Shopcart");
    		
		   if($run=="add")
		   {
		   	
	   			$q = $this->db->query("select price from ".table("food")." where foodid=".$_POST["foodid"]);
	   			$_price = $q->row_array();
	   			$num_price = $_price["price"]*intval($_POST["num"]);
	   			$uquery  = $this->db->query("select balance from ".table("users")." where userid=".$this->userdata["userid"]);
	   			$user_price = $uquery->row_array();
	   			if($num_price>$user_price["balance"])
	   			{
	   				$result = array("error"=>1,"content"=>"您当前余额不足,不能订餐");
	   			}else
	   			{
	   				$this->shopcart->add(intval($_POST["foodid"]),intval($_POST["num"]));
	   				$result = array("error"=>0,"content"=>"","obj"=>$obj);
	   			}
		   		
		   		
		   }else if($run=="del")
		   {
		   	    $this->shopcart->del(intval($_POST["foodid"]),$_POST["num"]);
		   	    $result = array("error"=>0,"content"=>"","obj"=>$obj);
		   
		   }else if($run=="clear")
		   {
		   	 	$this->shopcart->clear();
		   	 	$result = array("error"=>0,"content"=>"","obj"=>$obj);
		   }
		   
    		
    	#}
    	echo json_encode($result);
    }
    function step($rand="")
    {

    	 $sessionid = $this->session->userdata("shopcart");
    	 if($sessionid)
    	 {
    	 	$foodarray = array_keys($sessionid);
    	 	$query = $this->db->query("select e.eatname,f.foodname,f.price,f.foodid from ".table("food")." as f left join ".table("eatery")." as e on f.eatid=e.eateryid where f.foodid in(".implode(",",$foodarray).")");
    	 	$rs = $query->result_array();
    	 	$result = array();
    	 	$totalprice = $totalnum = "";
    	 	foreach ($rs as $v)
    	 	{
    	 		$v["totalprice"] = $v["price"]*$sessionid[$v["foodid"]];
    	 		$v["num"] = $sessionid[$v["foodid"]];
    	 		$result[] = $v;
    	 		$totalnum+= $v["num"];
    	 		$totalprice+= $v["totalprice"];
    	 		
    	 	}
    	 	$this->tp->assign("totalprice",$totalprice);
    	 	$this->tp->assign("totalnum",$totalnum);
    	 	$this->tp->assign("carts",$result);
    	 	
    	 }
    	 $this->tp->show("step");
    }
    function finish()
    {
    	$sessionid = $this->session->userdata("shopcart");
    	$result = array("tip"=>"订餐失败","message"=>"您还没有订餐");
    	if($sessionid)
    	{
    		if(count($sessionid)>0)
    		{
    			$cart_data = $sessionid;
    			
    			$this->load->library("Shopcart");
    			$this->shopcart->clear();
    			
    			$insert = "INSERT INTO ".table("orders")."(
													userid ,
													companyid,
													foodid ,
													foodnum,
													foodprice
													)
													VALUES ";
    			$rowtpl = "(%s,%s,%s,%s,%s),";
    			$rows = "";
    			
    			
    			$foodids = array_keys($cart_data);
				$query = $this->db->query("select price,foodid from ".table("food")." where foodid in(".implode(",",$foodids).")");
				$rs = $query->result_array();
				$fomat_cart = array();
				if(is_array($rs))
				{
					foreach ($rs as $v)
					{
						$fomat_cart[$v["foodid"]] = array($v["price"],$cart_data[$v["foodid"]]);
					}
				}
    			
    			
    			foreach ($fomat_cart as $key=>$v)
    			{
    				
    				$rows.=sprintf($rowtpl,$this->userdata["userid"],$this->userdata["companyid"],$key,$v[1],$v[0]);
    			}
    			$insert.=substr($rows,0,-1);
    			$this->db->query($insert);
    			$result = array("tip"=>"订餐成功","message"=>"系统已经收到您的订单,将会尽快处理");
    			$cart_data = "";
    		}
    	}
    	$this->tp->assign("re",$result);
    	$this->tp->show("step_info");
    }
    function mylist($page="")
    {
    	//$this->session->sess_destroy();

    	if($this->userdata)
    	{

    	   $query = $this->db->query("select s.*,f.foodname from ".table("orders")." as s left join ".table("food")." as f on s.foodid=f.foodid where date(s.createtime)='".date("Y-m-d")."' and s.userid=".$this->userdata["userid"]);
    	   $today = $query->result_array();
    	   $_today = array();
    	   if(is_array($today))
    	   {
    	   	 
    	   	 foreach ($today as $t)
    	   	 {
    	   	 	$t["foodname"] = get_team_orders($this->db,$t);
    	   	 	$_today[] = $t;
    	   	 }
    	   }
    	   
    	   
    	
    	   $page = $page==""?1:$page;
    	   $this->jypage->SetAttr(array(
			  'table'=>table("orders")." as s left join ".table("food")." as f on s.foodid=f.foodid",
			  'pagesize'=>10,
			  'page'=>$page,
			  'key'=>'s.ordersid',
			  'field'=>array("s.*","f.foodname"),
    	      'condition'=>" order by s.ordersid desc",
			  'where'=>"s.userid=".$this->userdata["userid"]." and s.isdo=1",
		      'pageurl'=>_baseurl_."orders/mylist/",
			  ));
		 $this->jypage->SetDb($this->db);
		
		 $pagelist = $this->jypage->pages();
		 
    	 $_pagelist = array();
		 if(is_array($pagelist))
		 {
		 	
		 	foreach ($pagelist["ZeroPage"] as $pages)
		 	{
		 		
		 		$pages["foodname"] = get_team_orders($this->db,$pages);
		 		$_pagelist[] = $pages;
		 	}
		 }
		 
		 
		 $pagestr = $this->jypage->SetPageStr();
    	
		 $this->tp->assign("pagestr",$pagestr);
		 $this->tp->assign("today",$_today);
		 $this->tp->assign("istoday",count($today));
		 $this->tp->assign("pagelist",$_pagelist);
      } 
		 
    	$this->tp->show("orders_my");
    }
    function expense($p="")
    {
    	
    	   $page = empty($p)?1:$p;
    	   if(!empty($this->userdata["userid"]))
    	   {
    	   	
    	   		$this->jypage->SetAttr(array(
			  'table'=>table("orders")." as s left join ".table("food")." as f on s.foodid=f.foodid",
			  'pagesize'=>10,
			  'page'=>$page,
			  'key'=>'s.ordersid',
			  'field'=>array("s.*","f.foodname"),
			  'where'=>"s.userid=".$this->userdata["userid"],
		      'pageurl'=>_baseurl_."orders/expense/",
			  ));
			 $this->jypage->SetDb($this->db);
			
			 $pagelist = $this->jypage->pages();
			 $_pagelist = array();
			 if(is_array($pagelist))
			 {
			 	
			 	foreach ($pagelist["ZeroPage"] as $pages)
			 	{
			 		
			 		$pages["foodname"] = get_team_orders($this->db,$pages);
			 		$_pagelist[] = $pages;
			 	}
			 }
			 
			 $pagestr = $this->jypage->SetPageStr();
	    	
			 
			 
			 #计算消费总额
			 $query_sum = $this->db->query("select foodprice,foodnum from ".table("orders")." where userid=".$this->userdata["userid"]." and isdo=1");
			 $person_expense = $query_sum->result_array();
			 $foodprice = 0;
			 if(!empty($person_expense))
			 {
			 	foreach ($person_expense as $person)
			 	{
			 		$foodprice+=$person["foodprice"]*$person["foodnum"];
			 	}
			 }
			 
			 $query_price = $this->db->query("select sum(price) as price from ".table("topup")." where userid=".$this->userdata["userid"]);
			 $pay_price = $query_price->row_array();
			 
			 
			 $user_price = $this->db->query("select balance from ".table("users")." where userid=".$this->userdata["userid"]);
			 $userprice = $user_price->row_array();
			 
			
			 #充值总金额
			 
			 
			 
			 $this->tp->assign("person_expense",$foodprice);
			 
			 $this->tp->assign("pay_price",$pay_price["price"]);
			 
			 $this->tp->assign("userprice",$userprice["balance"]);
			 
	    	$this->tp->assign("pagestr",$pagestr);
			$this->tp->assign("pagelist",$_pagelist);
    	   }
    	   
    	   
    	$this->tp->show("expense");
    	
    }
    function pay($p="")
    {
    	 $page = empty($p)?1:$p;

    	  if(!empty($this->userdata["userid"]))
    	   {
    	   		$this->jypage->SetAttr(array(
			  'table'=>table("topup"),
			  'pagesize'=>10,
			  'page'=>$page,
			  'key'=>'topupid',
			
			  'where'=>"userid=".$this->userdata["userid"],
		      'pageurl'=>_baseurl_."orders/pay/",
			  ));
			 $this->jypage->SetDb($this->db);
			
			 $pagelist = $this->jypage->pages();
			 $pagestr = $this->jypage->SetPageStr();
			 
			 #计算消费总额
			 $query_sum = $this->db->query("select foodprice,foodnum from ".table("orders")." where userid=".$this->userdata["userid"]." and isdo=1");
			 $person_expense = $query_sum->result_array();
			 
    	   	 $foodprice = 0;
			 if(!empty($person_expense))
			 {
			 	foreach ($person_expense as $person)
			 	{
			 		$foodprice+=$person["foodprice"]*$person["foodnum"];
			 	}
			 }
			 
			 
			 $query_price = $this->db->query("select sum(price) as price from ".table("topup")." where userid=".$this->userdata["userid"]);
			 $pay_price = $query_price->row_array();
			 
			 
			 $user_price = $this->db->query("select balance from ".table("users")." where userid=".$this->userdata["userid"]);
			 $userprice = $user_price->row_array();
			 
			
			 #充值总金额
			 
			 
			 
			 $this->tp->assign("person_expense",$foodprice);
			 
			 $this->tp->assign("pay_price",$pay_price["price"]);
			 
			 $this->tp->assign("userprice",$userprice["balance"]);
			 
			 
			 $this->tp->assign("pagestr",$pagestr);
			$this->tp->assign("pagelist",$pagelist["ZeroPage"]);
			 $pagestr = $this->jypage->SetPageStr();
    	   }
    	 
    	 
    	$this->tp->show("pay");
    }
    function myorders()
    {
    	$orderid = $_POST["orderid"];
    	
    	$result = array("error"=>1,"content"=>"退单失败");
    	if($orderid>0)
    	{
    		if(dotime($this->userdata["cartend"]))
    		{
    			$this->db->query("delete from ".table("orders")." where ordersid=".$orderid);
    			$result = array("error"=>0,"content"=>"退单成功");
    			
    		}else
    		{
    			$result = array("error"=>1,"content"=>"该时间段内不能退单");
    		}
    		
    	}
    	echo json_encode($result);
    }
    
    
	function setpass()
    {
    	
    	$this->tp->show("setpass");
    }
    function savepass()
    {
    	
    	$oldpassword = isset($_POST["oldpassword"])?$_POST["oldpassword"]:"";
    	$password = isset($_POST["password"])?$_POST["password"]:"";
    	if(empty($oldpassword) || empty($password))
    	{
    		s("密码不能为空",_baseurl_."orders/setpass/");
    	}else
    	{
    		$q = $this->db->query("select password from ".table("users")." where userid=".$this->userdata["userid"]);
    		$row = $q->row_array();
    		if(md5($oldpassword)==$row["password"])
    		{
    			$this->db->query("update ".table("users")." set password='".md5($password)."' where userid=".$this->userdata["userid"]);
	    		$this->session->set_userdata("memberdata","");
		    	if(!empty($_COOKIE["userid"]))
		    	{
		    		set_cookie("userid","",-1);
		    	}
		    	s("密码修改成功,请重新输入新的密码进入系统",_baseurl_."orders");
    			
    		}else
    		{
    			s("请输入正确的原密码",_baseurl_."orders/setpass/");
    		}
    	}
    	
    }
    function updateuser()#修改用户余额
    {
    	$query = $this->db->query("select * from ".table("users")." where companyid=1");
    	$user = $query->result_array();
    	foreach ($user as $u)
    	{
    		$price = self::checks($u['userid'],'');
    		$last = $this->db->query("select moneyRemain from dmc010079_db.tipcat_users where userName='".$u['username']."'");
    		$lastprice = $last->row_array();
    		$last_price = 0;
    		
    		if(!empty($lastprice) && $lastprice["moneyRemain"]>0)
    		{
    			$last_price = $lastprice["moneyRemain"]/10000;
    		}
    		$newprice = $last_price+$price;
    		$this->db->query("update ".table("users")." set balance='".$newprice."' where userid=".$u['userid']);
    	}
        echo 'update all user price finish!';
    	
    }
    function checks($checkid,$view="view")#检 查个人帐户情况
    {
    	
    	 #计算消费总额
		 $query_sum = $this->db->query("select foodprice,foodnum from ".table("orders")." where userid=".$checkid." and isdo=1");
		 $person_expense = $query_sum->result_array();
		 
		 $foodprice = 0;
		 foreach ($person_expense as $t)
		 {
		 	
		 	$foodprice+=$t["foodprice"]*$t["foodnum"];
		 }
		 $query_price = $this->db->query("select sum(price) as price from ".table("topup")." where userid=".$checkid);
		 $pay_price = $query_price->row_array();
		 if($view!="view")
		 {
		 	$info = $pay_price['price']-$foodprice;
		 	return $info;
		 }else
		 {
		 	$info = '消费总额:'.$foodprice."<br />";
		    $info.= '充值总额:'.$pay_price['price']."<br />";
		    $info.= '用户余额:'.($pay_price['price']-$foodprice)."<br />";
		    A($info);
		 }
		 
    }
    function checkall()#计算总金额
    {
    	
    	$query_sum = $this->db->query("select foodprice,foodnum from ".table("orders")." where companyid=1 and isdo=1");
		$person_expense = $query_sum->result_array();
		$foodprice = 0;
		foreach ($person_expense as $f)
		{
			$foodprice+=$f["foodprice"]*$f["foodnum"];
		}
		
		
		
		 $query_price = $this->db->query("select sum(price) as price from ".table("topup")." where companyid=1");
		 $pay_price = $query_price->row_array();
		
		 $info = '消费总额:'.$foodprice."<br />";
		 $info.= '充值总额:'.$pay_price['price']."<br />";
		
		 $info.= '余额:'.($pay_price['price']-$foodprice)."<br />";
		 echo $info;
		
    }
    function checkprice()#更改菜价
    {
    	$query_sum = $this->db->query("select o.*,f.price from ".table("orders")." as o left join ".table("users")." as u on o.userid=u.userid left join ".table('food')." as f on o.foodid=f.foodid where u.companyid=1 and o.isdo=1 and o.foodprice!=f.price order by o.ordersid desc");
		$person_expense = $query_sum->result_array();
		foreach ($person_expense as $f)
		{
			
			$this->db->query("update ".table("orders")." set foodprice='".$f["price"]."' where ordersid=".$f["ordersid"]);
			
		}
		echo 'update foodprice finish!';
    	
    }
    function checkuser()
    {
    	self::checks(55,'view');
    	
    }
}    
?>